"""
Vehicle manipulation views.
"""

from django.http import HttpResponse
from django.shortcuts import get_list_or_404
from django.contrib.auth.decorators import login_required

from track.models import Vehicle
from track.models import Position

from track.itinerary import getAdvancement

@login_required
def move(request, moveType, x, y, vehicle=None):
  """Translate or reposition a vehicle, and if necessary, calculate its new checkpoint data."""
  
  vehicles = Vehicle.objects.all()
  
  if vehicle != None:
    vehicles = vehicles.filter(slug=vehicle)
  
  vehicles = get_list_or_404(vehicles, user=request.user)
  
  x = float(x)
  y = float(y)
  
  for v in vehicles:
    if moveType == 'set':
      v.x = x % 360
      v.y = min(max(y, -Vehicle.maxLatitude), Vehicle.maxLatitude)
    else:
      v.x = (v.x + x) % 360
      v.y = min(max(v.y + y, -Vehicle.maxLatitude), Vehicle.maxLatitude)
    
    v.x = v.x % 360
    
    if v.checkpoint:
      # This vehicle already has a checkpoint ; this means he is on an
      # itinerary, and that we need to update his position
      v.checkpoint, v.advancement = getAdvancement(
        v.checkpoint.itinerary, v.x, v.y)
    
    v.position_set.create(x=v.x, y=v.y, checkpoint=v.checkpoint, advancement=v.advancement)
    v.save()
  
  return HttpResponse()
